package com.njworkorder.Controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.njworkorder.Entity.*;
import com.njworkorder.Service.MeteringUseService;
import com.njworkorder.Service.PlanMonthlyAllocationService;
import com.njworkorder.Service.PlanService;
import com.njworkorder.Service.TasksNumService;
import com.njworkorder.Utils.Result;
import com.njworkorder.Utils.ResultUtil;
import com.njworkorder.Utils.WebClientUtil;
import com.njworkorder.VO.AssignmentProgressVos.DRInfo;
import com.njworkorder.VO.PMAVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import net.sf.jsqlparser.expression.StringValue;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.*;
import java.util.concurrent.CompletableFuture;

@Tag(name = "京沪工区api")
@RestController
@RequestMapping("/JhWorkspaceApi")
public class JhWorkspaceApiController {

    //获取⼯区列表url
    private static final String queryAllWorkAreaListUrl = "https://qianhe-uzising.lingyunzhineng.com/datagateway/api/v1/openapi/queryAllWorkAreaList";
    //获取⼯程量清单数量url
    private static final String queryBillQuantitieNumsUrl = "https://qianhe-uzising.lingyunzhineng.com/datagateway/api/v1/openapi/queryBillQuantitieNums";

    public static final String url = "https://qianhe-uzising.lingyunzhineng.com/qsyhxc";


    private final TasksNumService tasksNumService;
    private final MeteringUseService meteringUseService;
    private final PlanMonthlyAllocationService planMonthlyAllocationService;
    public JhWorkspaceApiController(TasksNumService tasksNumService, MeteringUseService meteringUseService,
                                    PlanMonthlyAllocationService planMonthlyAllocationService) {
        this.tasksNumService = tasksNumService;
        this.meteringUseService = meteringUseService;
        this.planMonthlyAllocationService = planMonthlyAllocationService;
    }



    @Operation(summary = "获取⼯区列表")
    @GetMapping("/queryAllWorkAreaList")
    public String queryAllWorkAreaList() {
        return WebClientUtil.post(queryAllWorkAreaListUrl, new HashMap<String, String>(), getHeaderMap(), String.class).block();
    }

    @Operation(summary = "获取⼯程量清单数量")
    @GetMapping("/queryBillQuantitieNums")
    public String queryBillQuantitieNums(@Schema(description = "开始时间") @RequestParam(value = "startTime") String startTime,
                                         @Schema(description = "结束时间") @RequestParam(value = "endTime") String endTime,
                                         @Schema(description = "该参数取⼯区信息接⼝中的qsid") @RequestParam(value = "qsid") String qsid,
                                         @Schema(description = "项⽬编号") @RequestParam(value = "projectCode") String projectCode) {
        Map<String, String> body = new HashMap<>();
        body.put("startTime",startTime);
        body.put("endTime",endTime);
        body.put("qsid",qsid);
        body.put("projectCode",projectCode);
        return WebClientUtil.post(queryBillQuantitieNumsUrl,body, getHeaderMap(), String.class).block();
    }


    @Operation(summary = "养护报表 - 巡查与检查 获取总数")
    @GetMapping("/getSpecialCountByStartEndTime")
    public String getSpecialCountByStartEndTime(@Schema(description = "该参数取⼯区信息接⼝中的orgCode") @RequestParam(value = "orgCode",required = false) String orgCode,
                                                @Schema(description = "格式为： 2025-06-07 - 2025-06-08") @RequestParam(value = "begin",required = false) String begin){

        Map<String, String> pam = new HashMap<>();
        if(begin != null){
            pam.put("begin",begin);
        }
        if (orgCode != null){
            pam.put("orgCode",orgCode);
        }
        return WebClientUtil.get(url + "/openapi/getSpecialCountByStartEndTime",pam, getHeaderMap(), String.class).block();
    }


    @Operation(summary = "养护报表 - 巡查与检查接⼝列表信息获取")
    @GetMapping("/getSpecialAbstractByStartEndTime")
    public String getSpecialAbstractByStartEndTime(@RequestParam(value = "pageNum") String pageNum,
                                                   @RequestParam(value = "pageSize") String pageSize,
                                                   @Schema(description = "该参数取⼯区信息接⼝中的orgCode") @RequestParam(value = "orgCode") String orgCode,
                                                   @Schema(description = "格式为： 2025-06-07 - 2025-06-08") @RequestParam(value = "begin") String begin) {
        Map<String, String> pam = new HashMap<>();
        pam.put("pageNum",pageNum);
        pam.put("pageSize",pageSize);
        pam.put("begin",begin);
        pam.put("orgCode",orgCode);
        return WebClientUtil.get(url + "/openapi/getSpecialAbstractByStartEndTime",pam, getHeaderMap(), String.class).block();
    }

    @Operation(summary = "养护报表 - 根据巡检id获取巡检和病害详情")
    @GetMapping("/getSpecialInfoById")
    public String getSpecialInfoById(@Schema(description = "巡检id") @RequestParam(value = "specialId",required = false) String specialId){
        Map<String, String> pam = new HashMap<>();
        if(specialId != null){
            pam.put("specialId",specialId);
        }
        return WebClientUtil.get(url + "/openapi/getSpecialInfoById",pam, getHeaderMap(), String.class).block();
    }


    @Operation(summary = "养护报表 - 根据部⻔id获取任务通知与反馈数量")
    @GetMapping("/getApplicationCount")
    public String getApplicationCount(@RequestParam(value = "startTime") String startTime,
                                      @RequestParam(value = "endTime") String endTime,
                                      @Schema(description = "该参数取⼯区信息接⼝中的orgCode") @RequestParam(value = "orgCode") String orgCode,
                                      @Schema(description = "0表示申请，1表示反馈") @RequestParam(value = "status") String status){
        Map<String, String> pam = new HashMap<>();
        pam.put("startTime",startTime);
        pam.put("endTime",endTime);
        pam.put("status",status);
        pam.put("orgCode",orgCode);
        return WebClientUtil.get(url + "/openapi/getApplicationCount",pam, getHeaderMap(), String.class).block();
    }


    @Operation(summary = "查询工区下路线列表")
    @GetMapping("/queryWorkAreaRoadList")
    public String queryWorkAreaRoadList(@Schema(description = "工区id") @RequestParam(value = "qsid") String qsid){
        Map<String, String> pam = new HashMap<>();
        pam.put("qsid",qsid);

        Map<String, String> headerMap = getHeaderMap();
        headerMap.put("Content-Type","application/json");

        return WebClientUtil.post("https://qianhe-uzising.lingyunzhineng.com/datagateway/api/v1/openapi/queryWorkAreaRoadList",pam, headerMap, String.class).block();
    }

    @Operation(summary = "获取巡查任务数信息")
    @GetMapping("/getTasksNumByDay")
    public Result<Map<String, Object>> getTasksNumByDay(@RequestParam(value = "days",required = false,defaultValue = "7") int days) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        LocalDate today = LocalDate.now();
        String sTime = today.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate tomorrow = today.plusDays(1);
        String eTime = tomorrow.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        String format = String.format("%s - %s", sTime, eTime);

        String res = getSpecialCountByStartEndTime("491", format);
        JSONObject jsonObject = JSONObject.parseObject(res);

        int sumCount = 0;
        if (jsonObject != null) {

            int result = jsonObject.getIntValue("result");
            tasksNumService.updateTasksNum(result);


            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_MONTH, -days); // 减去指定天数
            Date time = calendar.getTime();// 返回Date对象

            LambdaQueryWrapper<TasksNum>  wrapper = new LambdaQueryWrapper<>();
            wrapper.ge(TasksNum::getCreateTime,time);
            List<TasksNum> list = tasksNumService.list(wrapper);

            List<String> pastDays = getPastDays(days);

            List<Map<String,Object>> mapList = new ArrayList<>();
            Map<String,Object>  map;
            for (int i=0;i<pastDays.size();i++) {

                if(i + 1 == pastDays.size()){
                    map = new HashMap<>();
                    map.put("date",sTime);
                    map.put("num",result);
                    sumCount += result;
                }else{
                    map = new HashMap<>();

                    String dat = pastDays.get(i);
                    Date sdfdate = sdf.parse(dat);

                    List<TasksNum> list1 = list.stream().filter(f -> f.getCreateTime().equals(sdfdate)).toList();
                    if(!list1.isEmpty()){
                        map.put("date",dat);
                        map.put("num",list1.getFirst().getNum());
                        sumCount += list1.getFirst().getNum();
                    }else {
                        map.put("date",dat);
                        map.put("num",0);
                    }
                }
                mapList.add(map);
            }

            Map<String,Object> data = new HashMap<>();
            data.put("sumCount",sumCount);
            data.put("mapList",mapList);
            return ResultUtil.success(data);
        }
        return ResultUtil.success(new HashMap<>());
    }


    @Operation(summary = "综合管理-养护资金进度")
    @GetMapping("/getFinancialProgress")
    public Result<List<Map<String, Object>>> getFinancialProgress(@RequestParam(value = "planId", required = false) String planId,
                                                                  @RequestParam(value = "workspaceId", required = false) String workspaceId) {

        CompletableFuture<PMAVo> ratioValue = planMonthlyAllocationService.getRatioValue(planId);
        CompletableFuture<List<PlanMetering>> useTotal = planMonthlyAllocationService.getUseTotal(planId);
        CompletableFuture.allOf(ratioValue, useTotal).join();
        PMAVo pMAVo = ratioValue.join();
        List<PlanMetering> join = useTotal.join();

        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<String, Object> data;

        for (int i = 1; i <= 12; i++) {
            String m = String.valueOf(i);
            double useT = 0;
            List<PlanMetering> list = join.stream().filter(f -> f.getIsSpecial().equals(m)).toList();
            if (!list.isEmpty()) {
                BigDecimal bd = BigDecimal.valueOf(list.getFirst().getSpecialUnitPrice().doubleValue());
                BigDecimal divisor = BigDecimal.valueOf(10000);
                BigDecimal result = bd.divide(divisor, 2, RoundingMode.HALF_UP);
                useT = result.doubleValue();
            }

            data = new HashMap<>();
            data.put("month", i);
            data.put("plannedExpenses", pMAVo.getValueByMonth(i));
            data.put("actualCost", useT);
            mapList.add(data);
        }
        return ResultUtil.success(mapList);
    }





    public Map<String,String> getHeaderMap() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = format.format(new Date());
        String qsyhxcToken = getQsyhxcToken(format1);

        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("token", qsyhxcToken);
        headerMap.put("time", format1);
        return headerMap;
    }

    private String getQsyhxcToken(String format1) {
        try {
            String hmac = "HmacSHA256";
            String secret = "microvideo@2024";
            SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), hmac);
            Mac sha256_HMAC = Mac.getInstance(hmac);
            sha256_HMAC.init(secretKey);
            byte[] hash = sha256_HMAC.doFinal(format1.getBytes(StandardCharsets.UTF_8));
            return byte2Hex(hash);
        } catch (Exception e) {
            System.out.println("Error HmacSHA256 ===========>" + e.getMessage());
        }
        return "";
    }

    private String byte2Hex(byte[] bytes) {
        StringBuilder stringBuffer = new StringBuilder();
        String temp = null;
        for (byte aByte : bytes) {
            temp = Integer.toHexString(aByte & 0xFF);
            if (temp.length() == 1) {
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

    public List<String> getPastDays(int days) {
        List<String> dateList = new ArrayList<>();
        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for (int i = days - 1; i >= 0; i--) {
            LocalDate date = today.minusDays(i);
            dateList.add(date.format(formatter));
        }
        return dateList;
    }
}
